package work.lianbiao;

import work.ListNode;

import java.util.HashMap;
import java.util.Map;

public class Problem141 {
//    public boolean hasCycle(ListNode head) {
//        Map<Integer, ListNode> map = new HashMap<>();
//        int i = 0;
//        while (head != null) {
//            if (map.containsValue(head)) {
//                return true;
//            } else {
//                map.put(i, head);
//                i++;
//                head = head.next;
//            }
//        }
//        return false;
//    }

    public static void main(String[] args) {

    }


    public ListNode hasCycle1(ListNode head) {

        ListNode fast = head;
        ListNode slow = head;
        while (fast != slow) {
            if (fast == null || fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return fast;
    }

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != slow) {
            if (fast == null || fast.next == null) {
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;
    }



}
